package com.example.actearly_revised;

import java.util.Calendar;

import com.example.actearly_revised.R;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;

public class LoginView extends Activity {
	public SQLogic entry;

	Button submitButton;
	EditText childInput; 
	EditText parentInput;
	EditText doctorInput;
	EditText dateInput;
	EditText emailInput;
	EditText DocEmailInput;
	DialogFragment newFragment;
	RadioGroup GenderButtons;
	RadioButton MaleButton;
	RadioButton FemaleButton;
	Intent p_intent;
	boolean noUsers;
	boolean add;
	static int currentProfile;
	static int genderChoice = -1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		super.onCreate(savedInstanceState);
		newFragment = new DatePickerFragment();
		setContentView(R.layout.activity_login_view);

		final Calendar c = Calendar.getInstance();

		//change font/color/text in action bar
		Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/futuram.ttf");
		//getActionBar().setTitle("Add/Edit Child Profile");


		//set font for textviews

		TextView optText = (TextView) findViewById(R.id.textView1);
		TextView optText1 = (TextView) findViewById(R.id.textView2);
		TextView optText2 = (TextView) findViewById(R.id.textView3);
		TextView optText3 = (TextView) findViewById(R.id.textView4);
		TextView optText4 = (TextView) findViewById(R.id.textView5);
		TextView optText5 = (TextView) findViewById(R.id.txtDocEmail);
		TextView optText6 = (TextView) findViewById(R.id.txtGender);
		TextView buttonText= (Button) findViewById(R.id.submitButton);

		optText1.setTypeface(customFont);
		optText1.setTextColor(Color.GRAY);
		optText1.setTextSize(14);

		optText.setTypeface(customFont);
		optText.setTextColor(Color.GRAY);
		optText.setTextSize(14);

		optText2.setTypeface(customFont);
		optText2.setTextColor(Color.GRAY);
		optText2.setTextSize(14);

		optText3.setTypeface(customFont);
		optText3.setTextColor(Color.GRAY);
		optText3.setTextSize(14);

		optText4.setTypeface(customFont);
		optText4.setTextColor(Color.GRAY);
		optText4.setTextSize(14);

		optText5.setTypeface(customFont);
		optText5.setTextColor(Color.GRAY);
		optText5.setTextSize(14);

		optText6.setTypeface(customFont);
		optText6.setTextColor(Color.GRAY);
		optText6.setTextSize(14);



		buttonText.setTypeface(customFont);

		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);

		// Create a new instance of DatePickerDialog and return it
		// return new DatePickerDialog(getActivity(), this, year, month, day);
		childInput = (EditText) findViewById(R.id.childName);
		parentInput = (EditText) findViewById(R.id.parentName);
		doctorInput = (EditText) findViewById(R.id.doctorName);
		dateInput = (EditText) findViewById(R.id.birthDate);
		emailInput = (EditText) findViewById(R.id.emailAddress);
		DocEmailInput = (EditText) findViewById(R.id.DocEmailAddress);
		submitButton = (Button) findViewById(R.id.submitButton);
		GenderButtons = (RadioGroup) findViewById(R.id.LbuttonGroup);
		MaleButton = (RadioButton) findViewById(R.id.MaleButton);
		FemaleButton = (RadioButton) findViewById(R.id.FemaleButton);

		childInput.setTypeface(customFont);
		parentInput.setTypeface(customFont);
		doctorInput.setTypeface(customFont);
		dateInput.setTypeface(customFont);
		emailInput.setTypeface(customFont);
		DocEmailInput.setTypeface(customFont);

		MaleButton.setTypeface(customFont);
		MaleButton.setTextColor(Color.GRAY);
		MaleButton.setTextSize(14);


		FemaleButton.setTypeface(customFont);
		FemaleButton.setTextColor(Color.GRAY);
		FemaleButton.setTextSize(14);



		p_intent = getIntent();
		noUsers = p_intent.getBooleanExtra("NoUsers", false); // if nothing given, assumes there are no users
		add = p_intent.getBooleanExtra("addselected",false);
		currentProfile = p_intent.getIntExtra("profile_number", 0); // zero means new profile to be made

		entry = new SQLogic(LoginView.this);
		User curr;
		if(currentProfile != 0)
		{
			entry.open();
			curr = entry.getUserData(currentProfile);
			entry.close();

			childInput.setText(curr.childname);
			parentInput.setText(curr.name);
			doctorInput.setText(curr.doctor);
			emailInput.setText(curr.email);
			dateInput.setText(curr.Birthdate);	
			DocEmailInput.setText(curr.docemail);

			if(curr.gender == 1){
				MaleButton.setChecked(true);
				FemaleButton.setChecked(false);
				genderChoice = 1;
			}
			else if(curr.gender == 2){
				MaleButton.setChecked(false);
				FemaleButton.setChecked(true);
				genderChoice = 2;
			}
			else{
				MaleButton.setChecked(false);
				FemaleButton.setChecked(false);
			}

			childInput.requestFocus();
			childInput.setSelection(childInput.getText().length());
		}

		Log.d("stuff", "stuff");



		MaleButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if(v.equals(MaleButton)){
					genderChoice = 1;
				}
			}
		});

		FemaleButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if(v.equals(FemaleButton)){
					genderChoice = 2;
				}
			}
		});


		dateInput.setOnClickListener(new View.OnClickListener() {
			@TargetApi(11)
			@SuppressLint("NewApi")
			public void onClick(View v) {
				//DialogFragment newFragment;
				((DatePickerFragment) newFragment).getEdit(dateInput);
				newFragment.show(getFragmentManager(), "datePicker");
				newFragment.onStop();

				/*		if(((DatePickerFragment) newFragment).getShowing()){
					String temp =  ((DatePickerFragment) newFragment).getDate();
					dateInput.setText(temp);
				}  */

			}

		});  

		dateInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@TargetApi(11)
			@SuppressLint("NewApi")
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					((DatePickerFragment) newFragment).getEdit(dateInput);
					newFragment.show(getFragmentManager(), "datePicker");
					newFragment.onStop();
				}

			}
		});   

		submitButton.setOnClickListener(new View.OnClickListener() {

			@TargetApi(11)
			@SuppressLint("NewApi")
			public void onClick(View v) {
				Context context = getApplicationContext();
				//CharSequence text = "Invalid ";
				int duration = Toast.LENGTH_SHORT;

				/*     final AccountManager manager = AccountManager.get(context);
		        final Account[] accounts = manager.getAccountsByType("com.google");
		        if (accounts[0].name != null) {
		            parentInput.setText(accounts[0].name);
		        }  */

				// thought this could work to get the parent name in the field, but doesn't work


				//		try{
				/*System.out.println("This is check 1");
				Log.d("usermanger", "try ");
				entry = new SQLogic(LoginView.this);
				entry.open();
				Log.d("usermanger", "open"); */

				boolean moveOn = true;
				long child = 0;
				System.out.println("ssssssss" +childInput.getText().toString());
				if(LoginVerify.verifyChildName(childInput.getText().toString()) ==  false){
					Log.d("error", "invalid child input");
					CharSequence text = "Invalid Child Name";
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					moveOn = false;
				}
				if(LoginVerify.verifyDoctorName(doctorInput.getText().toString()) == false){
					Log.d("error", "invalid doctor input");
					CharSequence text = "Invalid Doctor Name";
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					moveOn = false;
				}
				if(LoginVerify.verifyEmail(emailInput.getText().toString()) == false){
					Log.d("error", "invalid email input");
					CharSequence text = "Invalid User Email Address";
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					moveOn = false;
				}
				if(LoginVerify.verifyPaentName(parentInput.getText().toString()) == false){
					Log.d("error", "invalid parent input");
					CharSequence text = "Invalid Parent Name";
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					moveOn = false;
				}
				/*		if(LoginVerify.verifyEmail(DocEmailInput.getText().toString()) == false){
					Log.d("error", "invalid email input");
					CharSequence text = "Invalid Doctor Email Address";
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					moveOn = false;   
				}   */
				// person doesn't neccissarily know doctor's email

				if(LoginVerify.verifyGender(genderChoice) == false){
					Log.d("error", "invalid email input");
					CharSequence text = "Invalid Gender Choice";
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					moveOn = false;
				}

				if(moveOn){
					LoginVerify.setUserInfo(childInput.getText().toString(), doctorInput.getText().toString(), emailInput.getText().toString(), parentInput.getText().toString(), dateInput.getText().toString(), DocEmailInput.getText().toString(),genderChoice);
					Registration newRegistration = new Registration();
					newRegistration.setActOfCall(LoginView.this);
					child = newRegistration.update(Add(),currentProfile);  
					finish();

					if(Add()){ // update did an insert SQL command
						currentProfile = (int) child;
					}

					boolean optIn;
					entry.open();
					optIn = entry.OptInAnswered(currentProfile);
					entry.close();

					if(!optIn){	 // i.e. user has not answered the opt-in question				
						Intent intent = new Intent("com.example.actearly_revised.OptinScreen");
						intent.putExtra("profile_number", currentProfile);  
						startActivity(intent); 
					}
					else{
						Intent intent = new Intent("com.example.actearly_revised.PreTracker");
						intent.putExtra("profile_number", currentProfile);  
						startActivity(intent);
					}
				}
				/*	entry.createUserEntry(childInput.getText().toString(), parentInput.getText().toString(), 
						dateInput.getText().toString(), doctorInput.getText().toString(), 
						emailInput.getText().toString());
				System.out.println(entry.getUserData(1));
				entry.close();
				finish();*/

				// add code here to see if all fields have right info
				// child, DOB, doctor, parent, email

				// 
				//DialogFragment newFragment;
				//newFragment = new DatePickerFragment();

				//newFragment.show(getFragmentManager(), "datePicker");


				//}


				//		}
				//		catch (Exception e){}

				/* need code here! need to check if  this is a new account
				 * if this IS a new account, ask for opt-in, otherwise keep going
				 * 
				 */
				// go to Homepage if not first time
				// startActivity(new Intent("com.example.actearly_revised.TabHomePage"));  
				//go to Optin screen if it is first time




			}
		});


	}


	public boolean Add(){
		if(noUsers == true || add == true || currentProfile == 0){
			return true;
		}
		else
			return false;
	}

}

